package com.wenwo.util;

import com.wenwo.annotation.Log;
import com.wenwo.dto.MethodInvokeInfoDTO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: logging
 * @className: DtoBuilder.java
 * @description: DTO组装工具类
 * @author : ZY
 * @create: 2020年08月02日 18:28
 **/

public class DtoBuilder {

    public static MethodInvokeInfoDTO buildMethodInvokeInfoDTO(JoinPoint joinPoint, HttpServletRequest request,
                                                               Long startTime, String logType) {

        // 1.userId (此值需返回值来填充)
        String userId = "";
        // 2.username (此值需返回值来填充)
        String username = "";
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);
        // 3.描述
        String description = aopLog.value();
        // 4.logType
        //String logType = "INFO";
        String fullPath = joinPoint.getTarget().getClass().getName();
        // 5.包名
        String packageName = fullPath.substring(0, fullPath.lastIndexOf("."));
        // 6.类名
        String className = fullPath.substring(fullPath.lastIndexOf(".") + 1);
        // 7.方法名
        String methodName = signature.getName();
        // 8.方法参数
        StringBuilder params = new StringBuilder("{");
        // 参数值
        List<Object> argValues = new ArrayList<>(Arrays.asList(joinPoint.getArgs()));
        // 参数名称
        for (Object argValue : argValues) {
            params.append(argValue).append(" ");
        }
        // 9.requestIp
        String requestIp = StringUtil.getIp(request);
        // 10.耗时
        Long time = (System.currentTimeMillis() - startTime) / 1000;
        // 11.位置
        String address = "";
        // 12.浏览器
        String browser = StringUtil.getBrowser(request);
        // 13.异常堆栈信息
        String exceptionDetail = "";
        // 14.创建时间
        Date createTime = new Date();

        return MethodInvokeInfoDTO.builder()
                .userId(userId)
                .username(username)
                .description(description)
                .logType(logType)
                .packageName(packageName)
                .className(className)
                .methodName(methodName)
                .methodParams(params + "}")
                .requestIp(requestIp)
                .costTime(time)
                .address(address)
                .browser(browser)
                .exceptionDetail(exceptionDetail)
                .createTime(createTime)
                .build();
    }
}
